package com.itsu.admin.mvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJacksonResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Jerry.Su
 * @Date 2022/1/6 20:33
 */
@RestControllerAdvice
@Slf4j
public class JsonResponseBodyAdvice extends AbstractMappingJacksonResponseBodyAdvice {
    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
        Object value = bodyContainer.getValue();
        if (!(value instanceof Result)) {
            Result result = new Result();
            if (response instanceof ServletServerHttpResponse) {

                HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();
                HttpStatus status = HttpStatus.resolve(servletResponse.getStatus());
                if (status == null) {
                    status = HttpStatus.INTERNAL_SERVER_ERROR;
                }
                if (HttpStatus.OK == status) {
                    result.setCode(Result.SUCCESS_CODE);
                    result.setData(value);
                } else {
                    result.setCode(Result.ERROR_CODE);
                }
                bodyContainer.setValue(result);
            }
        } else {
            log.debug("response body type is instance of {}, do not need converter", Result.class);
        }
    }
}
